package com.yq.netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @ClassName NettyServer
 * @Description 服务端
 * @Author yaoqiang
 * @Date 2021/6/10 15:09
 * @Version 1.0
 */
public class NettyServer {
    public static void main(String[] args) {
        //创建bossGroup  workGroup
        /**
         1、创建两个线程组，bossgroup和workergroup
         2、bossgroup处理连接请求，workergroup处理业务，
         3、两个都是无限循环
         4、bossgroup和workergroup含有的子线程NioEventLoop的个数
         默认实际cpu核数*2

         */
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //创建服务端的启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            //使用练市编程进行设置
            /**
             * 设置两个线程组
             *设置两个线程组
             使用nioSocketChannel作为服务器的通道实现
             设置线程队列得到的连接个数
             设置保持活动连接状态
             创建一个通道测试对象（匿名对象） */
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //给pipeline设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new nettyServerHandler());
                        }
                    });
            System.out.println("...服务器 is ready...");
            //绑定一个端口并同步，生成了一个ChannelFuture
            ChannelFuture cf = bootstrap.bind(6668).sync();
            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        } catch (Exception ex) {

        } finally {
            bossGroup.shutdownGracefully();
        }
    }
}
